<template>
	<view class="content">
		<view class="top-container" id="top-container">
			<u-tabs :list="tabList" @click="switchTab" lineColor="#6072FF" :scrollable="false"
				itemStyle="padding-left: 100rpx; padding-right: 100rpx; height: 45px;font-weight:bold;" lineWidth="40"
				lineHeight="6"></u-tabs>
			<u-search :show-action="false" :placeholder="inputPla" class="input" height="70rpx"
				bgColor="rgb(247, 248, 247)" :animation="true" margin="30rpx 20rpx 10rpx 20rpx" searchIconShow="true"
				:showAction="true" @click="clickSearch()" @clickIcon="clickSearch()" @search="clickSearch()"
				@custom="clickSearch()" v-model="params.keyword"></u-search>
		</view>
		<scroll-view :style="{ height: height + 'px' }" scroll-y="true" :scroll-with-animation="true"
			:enable-back-to-top="true" @scrolltolower="reachBottom">
			<view class="modules" v-if="tabIndex === 0">
				<view class="content-distance" v-for="(item, index) in userList" :key="index">
					<view class="card">
						<view class="info u-p-30">
							<view class="name">
								{{item.name}}
								<text class="role" v-if="item.roleName">（{{item.roleName}}）</text>
							</view>
							<view class="u-m-t-20">
								<text>{{item.username}}</text>
								<text>场地权限{{item.siteCount}}家</text>
							</view>
						</view>
						<view class="btn-warp">
							<text class="del" @click="delAccount(item)">注销</text>
							<text class="edit" @click="navEdit(item)">编辑</text>
						</view>
					</view>
				</view>
				<u-empty v-if="userList.length == 0" text="暂无子账号数据" mode="list"
					icon="http://cdn.uviewui.com/uview/empty/list.svg" />
			</view>
			<view class="modules" v-else-if="tabIndex === 1">
				<view class="content-distance" v-for="(item,index) in roleList" :key="index">
					<view class="permission">
						<view class="content-top-box">
							<text class="name">{{item.name}}</text>
							<view class="content-top-box-operate">
								<text class="del" @click="delRole(item)">删除</text>
								<text class="edit" @click="navRole(item)">编辑</text>
							</view>
						</view>
						<view class="permission-container">
							<view class="scenario">
								<image class="permission-img" :src="`${staticFileUrl}/image/account/miniPrograms.svg`">
								</image>小程序后台({{item.appletCount}}项)
							</view>
							<view class="scenario">
								<image class="permission-img" :src="`${staticFileUrl}/image/account/pc.svg`"></image>
								网页后台({{item.pcCount}}项)
							</view>
						</view>
					</view>
				</view>
			</view>
			<u-loadmore :status="loadStatus" v-if="userList.length > 0" />
		</scroll-view>


		<view class="footer" id="footer">
			<view class="btn u-m-t-10">
				<u-button v-if="tabIndex === 0" type="primary" :customStyle="{height: '88rpx'}" shape="circle"
					@click="navAddAccount()">添加子账号</u-button>
				<u-button v-else-if="tabIndex === 1" type="primary" :customStyle="{height: '88rpx'}" shape="circle"
					@click="navAddRole()">添加角色权限</u-button>
			</view>
		</view>
		<u-modal :show="delShow" title="温馨提示" :showCancelButton="true" @cancel="closeDel" @confirm="confirm"
			:titleStyle="{color:'#FE404C',fontSize: '36rpx'}">
			<view class="slot-content">
				<rich-text :nodes="content"></rich-text>
			</view>
		</u-modal>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				staticFileUrl: this.$configPath.staticFileUrl,
				tabList: [{
					name: '子账号',
				}, {
					name: '角色权限',
				}, ],
				del: {
					backgroundColor: '#FE404C',
					color: '#fff',
					marginRight: '30rpx',
				},
				edit: {
					color: '#fff',
					marginRight: '20rpx',
				},
				userList: [],
				roleList: [],
				params: {
					pageNum: 1,
					pageSize: 10,
					userId: -1,
					pages: 1,
					keyword: '',
				},
				userId: 0,
				user: {},
				delShow: false,
				footerHeight: 0,
				height: 0,
				loadStatus: 'loadmore',
				content: '如果注销该账号，此子账号的任何信息和权限都将注销<br/>确定要注销该子账号？',
				tabIndex: 0,
				inputPla: '',
			}
		},
		onLoad() {
			this.initSubAccount(true);
			this.initRolePermission(true);
			this.tabChange();
		},
		onReady() {
			this.getPomHeight();
		},
		methods: {
			initSubAccount(reload){
				this.userList = [];
				this.params.pageNum = 1;
				this.findSubAccount(reload);
			},
			
			initRolePermission(reload){
				this.roleList = [];
				this.params.pageNum = 1;
				this.findRolePermissionList(reload)
			},
			
			tabChange(){
				if (this.tabIndex == 0){
					this.inputPla = "请输入手机号/姓名"
				} else {
					this.inputPla = "请输入角色名称"
				}
				this.params.keyword = '';
			},
			
			navRole(item) {
				// console.log('item', item);
				uni.navigateTo({
					url: '/pages-my/sub-account-v2/role-management/role-management?id=' + item.id
				})
			},
			//删除角色
			delRole(item) {
				const _that = this
				uni.showModal({
					title: '确认删除' + item.name + '吗？',
					content: '',
					success(res) {
						if (res.confirm) {
							_that.determineDelRole(item)
						}
					}
				});
			},
			determineDelRole(data) {
				// console.log(data, 'data')
				uni.showLoading({
					title: '删除中...',
					mask: true
				});
				this.$api('rolePermissionTemp.delRoleOrRolePermissionTemp', {
					id: data.id
				}).then(res => {
					if (res.status == 0) {
						uni.hideLoading();
						this.$helpers.toast('删除成功', 'success', 1000, true, () => {
							this.initRolePermission(false);
							this.initSubAccount(false);
						})
					} else {
						uni.hideLoading();
						getApp().err('删除不成功:' + res.msg);
					}
				})
			},

			//切换tab
			switchTab(item) {
				// console.log(item)
				this.tabIndex = item.index;
				this.tabChange();
			},
			//角色权限列表
			findRolePermissionList(relaod) {
				if (relaod){
					uni.showLoading({
						title: '加载中...',
						mask: true
					});
				}
				this.$api('role.findRoleList', this.params).then(res => {
					if (res.status == 0) {
						uni.hideLoading();
						this.params.pageNum = res.data.pageNum;
						this.params.totalPage = res.data.pages;
						this.loadStatus = res.data.pageNum === res.data.pages ? 'nomore' : 'loadmore';
						if (this.params.totalPage == 0) {
							this.loadStatus = 'nomore';
						}
						this.roleList = [...this.roleList, ...res.data.list]; //合并数组
					} else {
						uni.hideLoading();
						this.$helpers.toast('请求数据失败:' + res.msg);
					}
				}).catch(() => {
					uni.hideLoading();
				});
			},

			clickSearch() {
				if (this.tabIndex == 0){
					this.initSubAccount(false);
				} else {
					this.initRolePermission(false);
				}
			},
			// 查询子账号
			findSubAccount(reload, type) {
				if (reload){
					uni.showLoading({
						title: '加载中...',
						mask: true
					});
				}
				this.$api('user.findSubAccountV2', this.params).then(res => {
					if (type === 'refresh') {
						uni.stopPullDownRefresh();
					}
					if (res.status == 0) {
						this.params.pageNum = res.data.pageNum;
						this.params.totalPage = res.data.pages;
						this.loadStatus = res.data.pageNum === res.data.pages ? 'nomore' : 'loadmore';
						if (this.params.totalPage == 0) {
							this.loadStatus = 'nomore';
						}
						this.userList = [...this.userList, ...res.data.list]; //合并数组
						uni.hideLoading();
					} else {
						uni.hideLoading();
						this.$helpers.toast('请求数据失败:' + res.msg);
					}
				}).catch(() => {
					if (type === 'refresh') {
						uni.stopPullDownRefresh();
					}
					uni.hideLoading();
				});
			},
			delAccount(item) {
				// console.log("进入了吗")
				this.delShow = true;
				this.content = '如果注销该账号，此子账号的任何信息和权限都将删除。<div>确定要注销账号：<span style="color: #FE404C">' + item.username +
					'</span></div>';
				this.user.userId = item.id;
				this.user.username = item.username;
				this.user.name = item.name;
			},
			closeDel() {
				this.delShow = false
			},
			confirm() {
				this.deleteSubAccountByUserIdV2();
			},
			//注销子账号
			deleteSubAccountByUserIdV2() {
				uni.showLoading({
					title: '注销中...',
					mask: true
				});
				this.$api('user.deleteSubAccountByUserIdV2', this.user).then(res => {
					// console.log(res);
					if (res.status == 0) {
						uni.hideLoading();
						this.delShow = false;
						this.userList = [];
						this.$helpers.toast('注销成功', 'success', 2000, true, () => {
							this.findSubAccount(true)
						})
					} else {
						uni.hideLoading();
						getApp().err('注销不成功:' + res.msg);
					}
				})
			},
			// 添加子账号
			navAddAccount() {
				uni.navigateTo({
					url: '/pages-my/sub-account-v2/sub-account-edit/sub-account-edit-v2'
				});
			},
			//编辑子账号
			navEdit(item) {
				// console.log(item)
				let u = '/pages-my/sub-account-v2/sub-account-edit/sub-account-edit-v2?userId=' + item.id
				if (item.roleId){
					u = u.concat('&roleId=').concat(item.roleId)
				}
				uni.navigateTo({
					url: u
				})
			},
			//添加角色
			navAddRole() {
				uni.navigateTo({
					url: '/pages-my/sub-account-v2/role-management/role-management'
				});
			},

			//加载更多
			reachBottom() {
				if (this.loadStatus == 'nomore') {
					return;
				}

				this.loadStatus = 'loading';
				this.params.pageNum++;
				// console.log("进入了吗")
				this.findRolePermissionList()
				this.findSubAccount(false);
			},

			// 获取各个盒子的高度
			getPomHeight() {
				let query = wx.createSelectorQuery().in(this)
				query.select('#footer').boundingClientRect()
				query.select('#top-container').boundingClientRect()
				query.exec(res => {
					let windowHeight = wx.getSystemInfoSync().windowHeight
					this.height = windowHeight
					for (let i = 0; i < res.length; i++) {
						this.height -= res[i].height;
					}
				})
			}

		}
	}
</script>

<style lang="scss">
	.u-button--info {
		border-style: none !important;
	}

	.u-empty {
		margin-top: 270rpx !important;
	}

	.content {
		.top-container {
			background-color: #FFF;
			padding-bottom: 10rpx;

			.title-container {
				margin-top: 30rpx;
			}
		}

		.modules {
			padding-top: 25rpx;
		}

		.edit {
			padding: 30rpx;
		}

		.del {
			padding: 30rpx;
		}

		.content-distance {
			padding: 0rpx 25rpx;

			.role {
				color: rgba(0, 0, 0, 0.7);
				font-size: 24rpx;
			}
		}

		.permission {
			background-color: white;
			border-radius: 18rpx;

			//margin: 20rpx 30rpx;
			.permission-container {
				display: grid;
				grid-template-columns: 4fr 2fr;
				margin: 20rpx 30rpx;
				font-size: 26rpx;
				padding-bottom: 10rpx;
				color: rgba(0, 0, 0, 0.7);

				.permission-img {
					width: 27rpx;
					height: 27rpx;
					margin-right: 6rpx;
				}

				.scenario {
					display: flex;
					align-items: center;
					margin-bottom: 20rpx;
					width: 250rpx;
				}
			}

			.content-top-box {
				display: flex;
				justify-content: space-between;
				width: 100%;

				.name {    
					margin: 30rpx;
					font-size: 28rpx;
				}

				.content-top-box-operate {
					color: rgba(0, 0, 0, 0.7);
					display: flex;
					font-size: 26rpx;
				}
			}
		}

		.card {
			background-color: white;
			border-radius: 18rpx;
			//margin: 20rpx 30rpx;
			display: flex;
			justify-content: space-between;
			margin-bottom: 20rpx;

			.info {
				.name {
					width: 400rpx;
					font-size: $f-lg;
					color: rgba(0, 0, 0, 1);
				}

				view:nth-of-type(2) {
					font-size: $f-base;
					color: rgba(0, 0, 0, 0.7);

					text:nth-child(1) {
						border-right: 1rpx #e6e6e6 solid;
						padding-right: 10rpx;
					}

					text:nth-child(2) {
						padding-left: 10rpx;
					}
				}
			}

			.btn-warp {
				display: flex;
				align-items: flex-end;
				font-size: 26rpx;
			}
		}

		.slot-content {
			padding: $u-padding-large;
			text-align: center;
		}

		.footer {
			z-index: 99;
			border-top: 1px solid #fafafa;
			width: 100%;
			height: 166rpx;
			background-color: white;
			position: fixed;
			bottom: 0rpx;

			.btn {
				padding: $u-padding-medium;
			}
		}

		.loadmore {
			margin-top: 30rpx;
		}
	}
</style>
